/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Inloggen.java
 *
 * Created on 25-jan-2011, 14:04:22
 */
package nl.maxato.login;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import nl.maxato.controller.Controller;
import nl.maxato.domain.Athlete;
import nl.maxato.domain.Differences;
import nl.maxato.gui.CompareAthletesGUI;
import nl.maxato.gui.Main;
import nl.maxato.util.ConfigurationFile;
import nl.maxato.util.ParameterNames;
import nl.maxato.xmlservices.ConvertXMLData;
import nl.maxato.xmlservices.XMLService;

/**
 *
 * @author Danny
 */
public class Inlog extends javax.swing.JFrame implements KeyListener {

    ImageIcon[] images;
    String[] petStrings = {"cz", "de", "et", "gb", "gr", "es", "fr", "hu", "it", "nl", "pl", "pt", "ru"};
    String[] languagesStrings = {ParameterNames.languageCZECH, ParameterNames.languageDEUTSCH, ParameterNames.languageESTONIAN, ParameterNames.languageENGLISH, ParameterNames.languageGREEK, ParameterNames.languageESPANOL, ParameterNames.languageFRANCAIS, ParameterNames.languageHungarian, ParameterNames.languageITALIAN, ParameterNames.languageDUTCH, ParameterNames.languagePOLISH, ParameterNames.languagePORTUGUESE, ParameterNames.languageRUSSIAN};
    String cookie;
    InlogController inlogController;
    XMLService xmlService;
    ResourceBundle bundle;
    Controller controller;
    String language;
    String country;
    Locale locale;
    List<Athlete> athletesOld = new ArrayList<Athlete>();
    List<Athlete> athletesNew = new ArrayList<Athlete>();
    List<String> s;
    ConfigurationFile cf;

    /**
     * Creates new form Inloggen
     */
    public Inlog() {
        initComponents();
        cf = new ConfigurationFile();
        xmlService = XMLService.getInstance();
        inlogController = new InlogController();
        controller = new Controller();
       
        checkIfFoldersExists();
        checkIfConfigFileExists();

        if (cf.getLanguage().equals("")) {
            Locale defaultLocale = Locale.getDefault();
            getLanguague(defaultLocale.getLanguage());
        } else {
            getLanguague(cf.getLanguage());
        }
        tfPassword.addKeyListener(this);
        tfUsername.addKeyListener(this);

        if (InlogController.newVersionAvailable()) {
            JOptionPane.showMessageDialog(null, "dd", "Nieuwe Versie", 2);
        }
    }

    /**
     * Nodig om de lijst s te vullen, zodat je in de vergelijkerGUI kunt zien
     * welke eigenschap omhoog/omlaag is gegaan.
     */
    private void fillList() {
        s = new ArrayList<String>();
        s.add("");
        s.add(bundle.getString("AGE"));
        s.add(bundle.getString("WAGE"));
        s.add(bundle.getString("FANS"));
        s.add(bundle.getString("HEIGHT"));
        s.add(bundle.getString("WEIGHT"));
        s.add(bundle.getString("MAXID"));
        s.add(bundle.getString("FORM"));
        s.add(bundle.getString("EXPERIENCE"));
        s.add(bundle.getString("STRENGHT"));
        s.add(bundle.getString("STAMINA"));
        s.add(bundle.getString("SPEED"));
        s.add(bundle.getString("AGILITY"));
        s.add(bundle.getString("JUMP"));
        s.add(bundle.getString("THROWING"));
        s.add(bundle.getString("SPECIALTY1"));
        s.add(bundle.getString("SPECIALTY2"));

    }

    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if (key == KeyEvent.VK_ENTER) {
            Toolkit.getDefaultToolkit().beep();
            button_InloggenActionPerformed(null);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        setResizable(false);
        this.setLayout(new BorderLayout());
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width - 300) / 2, (screenSize.height - 145) / 2, 300, 145);
        // setResizable(false);
        jLabel_Username = new javax.swing.JLabel();
        jLabel_Password = new javax.swing.JLabel();
        tfUsername = new javax.swing.JTextField();
        button_Inloggen = new javax.swing.JButton();
        button_Cancel = new javax.swing.JButton();
        tfPassword = new javax.swing.JPasswordField();
        jLabel_Languague = new javax.swing.JLabel();
        //jComboBox1 = new javax.swing.JComboBox();
        images = new ImageIcon[petStrings.length];
        Integer[] intArray = new Integer[petStrings.length];
        for (int i = 0; i < petStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("img/" + petStrings[i] + ".png");
        }
        //Create the combo box.
        jComboBox1 = new JComboBox(intArray);
        ComboBoxRenderer renderer = new ComboBoxRenderer();
        jComboBox1.setRenderer(renderer);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        button_Inloggen.setMinimumSize(new java.awt.Dimension(80, 23));
        button_Inloggen.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_InloggenActionPerformed(evt);
            }
        });


//        button_Cancel.setText(bundle.getString("CANCEL")); // NOI18N
        button_Cancel.setMaximumSize(new java.awt.Dimension(80, 23));
        button_Cancel.setMinimumSize(new java.awt.Dimension(80, 23));
        button_Cancel.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_CancelActionPerformed(evt);
            }
        });

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        JPanel jPanelInlog = new JPanel();
        jPanelInlog.setBorder(new EmptyBorder(10, 10, 10, 10));

        jPanelInlog.setLayout(new GridLayout(0, 2, 5, 5));
        jLabel_Username.setPreferredSize(new Dimension(120, 5));
        jPanelInlog.add(jLabel_Username);
        jPanelInlog.add(tfUsername);
        jPanelInlog.add(jLabel_Password);
        jPanelInlog.add(tfPassword);
        jPanelInlog.add(jLabel_Languague);
        jPanelInlog.add(jComboBox1);
        jPanelInlog.add(button_Cancel);
        jPanelInlog.add(button_Inloggen);
        
        this.getContentPane().add(BorderLayout.CENTER, jPanelInlog);

        //javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        //getContentPane().setLayout(layout);
        //layout.setHorizontalGroup(
        //        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel_Languague).addComponent(jLabel_Password).addComponent(jLabel_Username)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addGroup(layout.createSequentialGroup().addComponent(button_Cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(button_Inloggen, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)).addComponent(jComboBox1, 0, 143, Short.MAX_VALUE).addComponent(tfUsername, javax.swing.GroupLayout.Alignment.LEADING).addComponent(tfPassword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)).addContainerGap(53, Short.MAX_VALUE)));
        //layout.setVerticalGroup(
        //        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(tfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel_Username)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel_Password)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jLabel_Languague)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(button_Inloggen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(button_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));

        //pack();
    }// </editor-fold>                        

    private void checkIfFoldersExists() {
        inlogController.checkIfFoldersExists("data");
        inlogController.checkIfFoldersExists("xml");
        inlogController.checkIfFoldersExists("xml/athletes");
    }

    private void button_InloggenActionPerformed(java.awt.event.ActionEvent evt) {

        try {
            String username = inlogController.checkUsername(tfUsername.getText());
            cookie = inlogController.signIn(username, tfPassword.getText());

            //controleren of je bent ingelogd
            if (inlogController.checkLogin() == true) {
                try {
                    athletesOld = xmlService.xmlToAthletes();
                } catch (Exception e) {
                    System.out.println("De map met atleten is leeg, maar methode gaat verder hoop ik?");
                }
                //Get XML files from server
                inlogController.getDataAthletes(cookie);
                inlogController.getData(cookie, "team");
                inlogController.getData(cookie, "world");
                inlogController.getData(cookie, "calendar");

                //Convert the XML athleetfile to list
                athletesNew = xmlService.xmlToAthletes();
                List<Differences> dfs = new ArrayList<Differences>();
                //Check if atletenOud is not empty
                if (athletesOld != null) {
                    //Compare Athlete Lists 
                    fillList();
                    dfs = controller.compareXMLFiles(athletesOld, athletesNew, 0, s);
                    //If there are any differences start the VergelijkerGUI
                }
                Main main = new Main(controller, athletesOld);
                main.setVisible(true);
                if (0 < dfs.size()) {
                    CompareAthletesGUI comparteAthletesGUI = new CompareAthletesGUI();
                    comparteAthletesGUI.setVisible(true);
                    comparteAthletesGUI.setComparesTable(dfs);
                }
                this.dispose();
            } else {

                String error = inlogController.getErrorLogin();
                System.out.println(error);
                if (error.equals("Login failed")) {
                    JOptionPane.showMessageDialog(null, bundle.getString("ERROR_WRONG_USERNAME_OR_PASSWORD"), bundle.getString("ERROR_SCREEN"), 2);
                } else {
                    JOptionPane.showMessageDialog(null, "Error: " + error, bundle.getString("ERROR_SCREEN"), 2);

                }
            }
        } catch (Exception ex) {
            Logger.getLogger(Inlog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void button_CancelActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
    }

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        /**
         * 0 - Deutsch 1 - English 2 - Espanol 3 - Francais 4 - Nederlands 5 -
         * Polski
         */
        if (jComboBox1.getSelectedIndex() == 0) {
            bundle = controller.getLanguague("cs");
        } else if (jComboBox1.getSelectedIndex() == 1) {
            bundle = controller.getLanguague("de");
        } else if (jComboBox1.getSelectedIndex() == 2) {
            bundle = controller.getLanguague("et");
        } else if (jComboBox1.getSelectedIndex() == 3) {
            bundle = controller.getLanguague("en");
        } else if (jComboBox1.getSelectedIndex() == 4) {
            bundle = controller.getLanguague("el");
        } else if (jComboBox1.getSelectedIndex() == 5) {
            bundle = controller.getLanguague("es");
        } else if (jComboBox1.getSelectedIndex() == 6) {
            bundle = controller.getLanguague("fr");
        } else if (jComboBox1.getSelectedIndex() == 7) {
            bundle = controller.getLanguague("hu");
        } else if (jComboBox1.getSelectedIndex() == 8) {
            bundle = controller.getLanguague("it");
        } else if (jComboBox1.getSelectedIndex() == 9) {
            bundle = controller.getLanguague("nl");
        } else if (jComboBox1.getSelectedIndex() == 10) {
            bundle = controller.getLanguague("pl");
        } else if (jComboBox1.getSelectedIndex() == 11) {
            bundle = controller.getLanguague("pt");
        } else if (jComboBox1.getSelectedIndex() == 12) {
            bundle = controller.getLanguague("ru");
        }
        translateGUI(bundle, jComboBox1.getSelectedIndex());
    }

    /**
     * Returns an ImageIcon, or null if the path was invalid.
     */
    protected static ImageIcon createImageIcon(String path) {
        //  java.net.URL imgURL = path;
        if (path != null) {
            return new ImageIcon(path);
        } else {
            System.err.println("Couldn't find image file: " + path);
            return null;
        }
    }

    private void translateGUI(ResourceBundle b, int selectedItem) {
        this.setTitle(b.getString("MAXATO_LOGIN"));

        //JLabels vertalen
        jLabel_Username.setText(b.getString("USERNAME") + ":");
        jLabel_Password.setText(b.getString("SECURITY_CODE") + ":");
        jLabel_Languague.setText(b.getString("LANGUAGE") + ":");

        //Buttons vertalen
        button_Cancel.setText(b.getString("CANCEL"));
        button_Inloggen.setText(b.getString("LOGIN"));
        //JCombobox vertalen en items toevoegen
        JComboBox cb = jComboBox1;
        cb.setSelectedIndex(selectedItem);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//zet de GUI om in Windows-look
        try {

            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            System.out.println("Unable to load Windows look and feel");
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Inlog().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton button_Cancel;
    private javax.swing.JButton button_Inloggen;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel_Languague;
    private javax.swing.JLabel jLabel_Password;
    private javax.swing.JLabel jLabel_Username;
    private javax.swing.JPasswordField tfPassword;
    private javax.swing.JTextField tfUsername;
    // End of variables declaration                   

    private void getLanguague(String waarde) {
        int selectedItemLanguague = 3;
        if (waarde.equals("cs")) {
            bundle = controller.getLanguague("cs");
            selectedItemLanguague = 0;
        } else if (waarde.equals("de")) {
            bundle = controller.getLanguague("de");
            selectedItemLanguague = 1;
        } else if (waarde.equals("et")) {
            bundle = controller.getLanguague("et");
            selectedItemLanguague = 2;
        } else if (waarde.equals("en")) {
            bundle = controller.getLanguague("en");
            selectedItemLanguague = 3;
        } else if (waarde.equals("el")) {
            bundle = controller.getLanguague("el");
            selectedItemLanguague = 4;
        } else if (waarde.equals("es")) {
            bundle = controller.getLanguague("es");
            selectedItemLanguague = 5;
        } else if (waarde.equals("fr")) {
            bundle = controller.getLanguague("fr");
            selectedItemLanguague = 6;
        } else if(waarde.equals("hu")) {
            bundle = controller.getLanguague("it");
            selectedItemLanguague = 7;
        } else if (waarde.equals("it")) {
            bundle = controller.getLanguague("it");
            selectedItemLanguague = 8;
        } else if (waarde.equals("nl")) {
            bundle = controller.getLanguague("nl");
            selectedItemLanguague = 9;
        } else if (waarde.equals("pl")) {
            bundle = controller.getLanguague("pl");
            selectedItemLanguague = 10;
        } else if (waarde.equals("pt")) {
            bundle = controller.getLanguague("pt");
            selectedItemLanguague = 11;
        } else if (waarde.equals("ru")) {
            bundle = controller.getLanguague("ru");
            selectedItemLanguague = 12;
        } else {
            bundle = controller.getLanguague("en");
            selectedItemLanguague = 1;
        }
        translateGUI(bundle, selectedItemLanguague);
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }

    private void checkIfConfigFileExists() {
        File file = new File("data/config.properties");
        boolean exists = file.exists();
        if (!exists) {
            try {
                file.createNewFile();
                Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                out.write("Language= \n Country=");
                out.close();
            } catch (Exception ex) {
                Logger.getLogger(Inlog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    class ComboBoxRenderer extends JLabel
            implements ListCellRenderer {

        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(LEFT);
            setVerticalAlignment(CENTER);
        }

        /*
         * This method finds the image and text corresponding to the selected
         * value and returns the label, set up to display the text and image.
         */
        public Component getListCellRendererComponent(
                JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
            //Get the selected index. (The index param isn't
            //always valid, so just use the value.)
            int selectedIndex = ((Integer) value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            //Set the icon and text.  If icon was null, say so.
            ImageIcon icon = images[selectedIndex];
            String language = languagesStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(language);
                setFont(list.getFont());
            } else {
                setUhOhText(language + " (no image available)",
                        list.getFont());
            }

            return this;
        }

        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}
